﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LCA.Community.Web.Models
{
    public static class StringSearchExtensions
    {
        private static double WordLike(this string searchSource, string searchTerm)
        {
            string ss = searchSource.ToLower();
            string st = searchTerm.ToLower();
            int parecido;
            int posicion;
            int posant;
            if (ss.Equals(st))
            {
                return 1;
            }
            else if (ss.Contains(st) || st.Contains(ss))
            {
                return ss.Length > st.Length ? (st.Length / (double)ss.Length) : (ss.Length / (double)st.Length);
            }
            else
            {
                int i = 0;
                parecido = 0;
                posicion = ss.IndexOf(st[i]);
                posant = 0;
                while (i < st.Length && posicion < ss.Length)
                {
                    if (posicion == -1)
                    {
                        posicion = posant;
                    }
                    else
                    {
                        posant = posicion;
                        ss = ss.Remove(posicion, 1);
                        parecido++;
                    }
                    i++;
                    try
                    {
                        posicion = ss.IndexOf(st[i], posicion);
                    }
                    catch (Exception)
                    { }
                }
                return parecido / (double)(ss.Length > st.Length ? ss.Length : st.Length);
            }
        }

        public static double Like(this string searchSource, string searchTerm)
        {
            double res = 0;
            int queryLength = 0;
            char[] separators = new char[] { ' ', ',', '.', ':', ';', '(', ')', '{', '}' };
            IList<string> searchTerms = new List<string>(searchTerm.Split(separators, StringSplitOptions.RemoveEmptyEntries));
            IList<string> searchSources = new List<string>(searchSource.Split(separators, StringSplitOptions.RemoveEmptyEntries));
            foreach (string s in searchTerms)
            {
                queryLength = queryLength + s.Length;
            }
            foreach (string s in searchTerms)
            {
                string p = (from e in searchSources
                            orderby e.WordLike(s) descending
                            select e).First<string>();
                res = res + p.WordLike(s) * (s.Length / queryLength);
                searchSources.Remove(p);
            }
            return res;
        }

        public static double Like(this string searchSource, string[] searchTerms)
        {
            return 0;
        }
    }
}